import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import errorCode from '@/const/errorCode'
import { getStore } from '@/utils/store'
import router from '../router'
import { Loading } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})
// 统计请求次数，避免重复loading ---start
let loadingRequestCount = 0
let loadingInstance

// const LOGIN_REQUEST_LIST = ['/admin/index/tenant/list', '/auth/oauth/token', '/admin/user/info', '/admin/menu/userMenu']
// function checkUrl(url) {
//   let res = true
//   for (const i of LOGIN_REQUEST_LIST) {
//     if (url.indexOf(i) !== -1) {
//       res = false
//       break
//     }
//   }
//   return res
// }

const requestArr = ['/admin/index/tenant/list', '/auth/oauth/token', '/admin/user/info', '/admin/menu/userMenu']

const showLoading = (url) => {
  console.log('loadingRequestCount', loadingRequestCount)
  if (requestArr.indexOf(url) === -1) {
    loadingInstance =
    Loading.service({ background: 'rgba(0, 0, 0, 0.6)' })
  }
  loadingRequestCount++
}

const hideLoading = (res) => {
  if (loadingRequestCount <= 0) return
  loadingRequestCount--
  if (loadingRequestCount === 0 && loadingInstance) {
    loadingInstance.close()
  }
}
// 统计请求次数，避免重复loading ---end

// request interceptor
service.interceptors.request.use(
  config => {
    // if (!requestMap.has(config.url)) {
    showLoading(config.url)
    // }
    // do something before request is sent
    if (getStore({ name: 'refresh_token' })) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      console.log('tenantid', getStore({ name: 'tenant_id' }))
      config.headers['Authorization'] = 'Bearer ' + getToken()
      config.headers['TENANT_ID'] = getStore({ name: 'tenant_id' })
      console.log(config.headers)
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // 响应拦截进来隐藏loading效果，此处采用延时处理是合并loading请求效果，避免多次请求loading关闭又开启 合并loading请求效果 避免重复请求
    setTimeout(() => {
      hideLoading(response.data)
    }, 200)

    // if the custom code is not 20000, it is judged as an error.
    // if (res.code !== 20000) {
    //   Message({
    //     message: res.message || 'Error',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })

    //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     // to re-login
    //     MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //       confirmButtonText: 'Re-Login',
    //       cancelButtonText: 'Cancel',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('user/FedLogOut').then(() => {
    //         location.reload()
    //       })
    //     })
    //   }
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    //   return res
    // }

    return res
  },
  error => {
    console.log('err' + error) // for debug
    // 响应拦截进来隐藏loading效果，此处采用延时处理是合并loading请求效果，避免多次请求loading关闭又开启 合并loading请求效果 避免重复请求
    setTimeout(() => {
      hideLoading()
    }, 200)
    const errMsg = error.toString()
    const code = errMsg.substr(errMsg.indexOf('code') + 5)
    Message({
      message: errorCode[code] || errorCode['500'],
      type: 'error',
      duration: 5 * 1000
    })
    console.log(parseInt(code))
    if (parseInt(code) === 401) {
      if (top.location !== location) {
        Message({
          message: '登录已失效，请退出后重新登录',
          type: 'error',
          duration: 100
        })
        store.dispatch('user/LogOut').then(() => {
          document.write("<div><img src='http://sv.s-gsun.com/img/404.png' style='width: 100%;'></div>")
        })
      } else {
        store.dispatch('user/LogOut').then(() => {
          router.push({ path: '/login' })
        })
      }
    }
    return Promise.reject(new Error(error))
  }
)

export default service
